<?php

namespace App\Service\delivery;
use App\Model\Applet;
use App\Model\AppletPlayletRel;
use App\Model\AppletPlayletRelDelivery;
use App\Model\DataBackhaulSetting;
use App\Model\DataSpread;
use App\Model\DataSpreadAdAccountLog;
use App\Model\DataSpreadPlatform;
use App\Model\Playlet;
use App\Model\Company;
use App\Model\AppletCompany;
use App\Model\PlayletEpisodes;
use App\Model\PlayletSpreadLimit;
use App\Model\RechargeTemplate;
use App\Service\CommicService;
use Hyperf\Utils\ApplicationContext;
use App\Common\Response\SystemCode;
use Hyperf\DbConnection\Db;

class DataSpreadService extends CommicService
{
    const cacheDuration = 60 * 15;
    public function __construct()
    {
        $container = ApplicationContext::getContainer();
        $this->redisService = $container->get(\Hyperf\Redis\Redis::class);
        $this->userAppletIds = $this->getUserAppletInfo();
    }


    const STATUS_ENABLE  = 1;


    public function search(Array $params){

        $keyword        = $params['keyword'] ?? '';
        $id             = $params['id'] ?? '';
        $pageSize       = $params['pageSize'] ?? 10;
        $page           = $params['page'] ?? 1;
        $applet_ids     = $params['applet_ids'] ?? '';
        $playlet_id     = $params['playlet_id'] ?? '';
        $delivery_user_id  = $params['delivery_user_id'] ?? '';
        if(empty($applet_ids)){
            return [];
        }
        //获取所拥有的
        if($applet_ids == '1'){
            //获取所有的小程序所绑定的短剧
            $applet_id =  $this->userAppletIds;
        }else{
            $applet_id =  [$applet_ids];
        }

        $query = DataSpread::query()
            ->leftJoin('applet','data_spread.applet_id','=','applet.id')
            ->leftJoin('playlet','data_spread.playlet_id','=','playlet.id')
            ->leftJoin('data_backhaul_setting','data_spread.backhaul_setting_id','=','data_backhaul_setting.id')
            ->leftJoin('recharge_template','data_spread.recharge_template_id','=','recharge_template.id')
            ->leftJoin('recharge_template as assistant','data_spread.assistant_recharge_template_id','=','assistant.id')
            ->leftJoin('recharge_template as retention','data_spread.retention_template_id','=','retention.id')
            ->leftJoin('system_company','data_spread.company_id','=','system_company.id')
            ->select(['data_spread.id','data_spread.name','data_spread.ad_account','data_spread.applet_id','data_spread.playlet_id','data_spread.company_id','data_spread.recharge_template_id'
                ,db::Raw('IFNULL(playlet.`alias_name`,playlet.`name`) as playlet_name'),'data_spread.playlet_number_name','data_spread.retention_template_id','data_spread.assistant_recharge_template_id','data_spread.playlet_number_num'
                ,'data_spread.playlet_number_num_pay','data_spread.playlet_number','data_spread.created_at','data_spread.updated_at','data_backhaul_setting.name as backhaul_setting_name'
                ,'recharge_template.name as recharge_template_name','applet.name as applet_name','system_company.name as company_name','assistant.name as recharge_assistant_template_name','retention.name as retention_template_name'
            ]);

        if ($keyword) {
            $query->orWhere([['data_spread.name', 'like', '%'.$keyword.'%']]);
        }
        if($playlet_id != '' && $playlet_id != 1){
            $query->where('data_spread.playlet_id',$playlet_id);
        }
        if(!empty($applet_id)){
            $query->whereIn('data_spread.applet_id',$applet_id);
        }
        if(!empty($id)){
            $query->where('data_spread.id',$id);
        }
        //根据用户获取ID
        $userInfo = $this->getUserAppletInfo(2);
        if($userInfo['role']['is_admin'] != 1){
            $query->where('data_spread.user_id',$userInfo['id']);
        }

        $models = $query->orderBy('data_spread.id','desc')->paginate($pageSize,['*'],'page',$page);
        $items = $models->items();
        $selectData = [];
        foreach ($items as $item){
            $data = $item->toArray();
            if($data['playlet_id'] == 37){
                $data['playlet_name']  = $data['playlet_name'].'(74集)';
            }
            if($data['playlet_id'] == 39){
                $data['playlet_name']  = $data['playlet_name'].'(75集)';
            }
            if(empty($data['backhaul_setting_name'])){
                $data['backhaul_setting_name']  = '不回传';
            }
//            if(!empty($item->applet)){
//                $data['applet_name']  = $item->applet->name;
//            }else{
//                $data['applet_name']  = '';
//            }
//            if(!empty($item->template)){
//                $data['recharge_template_name']  = $item->template->name;
//            }else{
//                $data['recharge_template_name']  = '';
//            }
//            if(!empty($item->assistantTemplate)){
//                $data['recharge_assistant_template_name']  = $item->assistantTemplate->name;
//            }else{
//                $data['recharge_assistant_template_name']  = '';
//            }
//            if(!empty($item->company)){
//                $data['company_name']  = $item->company->name;
//            }else{
//                $data['company_name']  = '';
//            }
//
            $selectData[] =$data;
        }
        $data = $models->toArray();
       // $data = $models;
        $data['data'] = $selectData;
        return $data;
    }

    public function createOrUpdate(Array $postData,$is_update=false,DataSpread $dataSpreadInfo = null){
        $name = $postData['name'];
        $applet_id = $postData['applet_id'];
        //$company_id = $postData['company_id'];
        $user_type =  $postData['user_type'] ?? 1;
        $playlet_id = $postData['playlet_id'];
        $recharge_template_id = $postData['recharge_template_id'] ?? 1;
        $assistant_recharge_template_id = !empty($postData['assistant_recharge_template_id']) ? $postData['assistant_recharge_template_id'] : 0;
        $retention_template_id = !empty($postData['retention_template_id']) ? $postData['retention_template_id'] : 0;
        $assistant_retention_template_id= !empty($postData['assistant_retention_template_id']) ? $postData['assistant_retention_template_id'] : 0;
        $spread_platform_id = $postData['spread_platform_id'];
        $playlet_number = $postData['playlet_number'];
        $playlet_number_num = $postData['playlet_number_num'];
        $ad_account = !empty($postData['ad_account']) ? trim($postData['ad_account']) : '';
        $playlet_number_num_pay = $postData['playlet_number_num_pay'];
        $recharge_template_type = $postData['recharge_template_type'];
        $operation_mode = !empty($postData['operation_mode']) ? $postData['operation_mode'] : 1;
        $backhaul_setting_id = !empty($postData['backhaul_setting_id']) ? $postData['backhaul_setting_id'] : 0;
        //根据用户获取ID
        $userInfo = $this->getUserAppletInfo(2);
        $company_id = $userInfo['company_id'];

        Db::beginTransaction();
        try {
//            var_dump($dataSpreadInfo);
            $model = !empty($dataSpreadInfo)? $dataSpreadInfo : new DataSpread();

            //查看公司是否存在
            $companyData = Company::query()->where(['id' => $company_id])->exists();
            if(empty($companyData)){
                throw new \Exception('公司不存在');
            }
            //查找小程序是否存在
            $appletData = Applet::query()->where(['id' => $applet_id])->first();
            if(empty($appletData)){
                throw new \Exception('请选择小程序');
            }
            //查看小程序和公司是否存在绑定关系
            $appletCompanyData = AppletCompany::query()->where(['company_id' => $company_id,'applet_id' => $applet_id])->exists();
            if(empty($appletCompanyData)){
                throw new \Exception('公司和小程序不存在绑定关系小程序');
            }
            //查找短剧是否存在
            $playletData = Playlet::query()->where(['id' => $playlet_id])->select(['id','name','album_id'])->first();
            if(empty($playletData)){
                throw new \Exception('短剧不存在');
            }
            //查找短剧是否属于这小程序
            $appletPlayletData = AppletPlayletRelDelivery::query()->where(['playlet_id' => $playlet_id,'applet_id'=>$applet_id ])->exists();
            if(empty($appletPlayletData)){
                throw new \Exception('短剧不属于这小程序');
            }
            //查询短剧是否拥有这集数
            $playletEpisodesData = PlayletEpisodes::query()->where(['playlet_id' => $playlet_id,'playlet_number'=>$playlet_number ])->select(['playlet_number_name','dy_episodes_id'])->first();
            if(empty($playletEpisodesData)){
                throw new \Exception('短剧不存在这集数');
            }
            //查询短剧是否拥有这集数
            $episodesData = PlayletEpisodes::query()->where(['playlet_id' => $playlet_id,'playlet_number'=>$playlet_number_num])->exists();
            if(empty($episodesData)){
                throw new \Exception('短剧不存在这付费集数');
            }

            if($playlet_number > $playlet_number_num){
                throw new \Exception('投放集数必须小于付费集数!');
            }
            //新增2023-11-27 短剧默认最高付费集数
            $limitInfo = PlayletSpreadLimit::query()->where(['playlet_id' => $playlet_id])->first();

            if(!empty($limitInfo)){

                if($playlet_number_num > $limitInfo->pay_episodes_number){
                    throw new \Exception('付费集数大于默认付费,默认付费集数为：'.$limitInfo->pay_episodes_number);
                }
            }

            if($recharge_template_type == 1){
                $recharge_template_id = 1;
            }else{
                //查询充值模板是否存在
                $rechargeTemplateData = RechargeTemplate::query()->where(['id' => $recharge_template_id,'company_id' => $company_id])->exists();
                if(empty($rechargeTemplateData)){
                    throw new \Exception('充值模板不存在,或者模板不属于该小程序');
                }
            }

            if(!empty($assistant_recharge_template_id) && $assistant_recharge_template_id != 1){

                //查询副充值模板是否存在
                $rechargeTemplateData = RechargeTemplate::query()->where(['id' => $assistant_recharge_template_id,'company_id' => $company_id])->exists();
                if(empty($rechargeTemplateData)){
                    throw new \Exception('充值模板不存在,或者模板不属于该小程序');
                }
            }
            if(!empty($retention_template_id)){

                //查询副充值模板是否存在
                $retentionTemplateData = RechargeTemplate::query()->where(['id' => $retention_template_id,'company_id' => $company_id])->exists();
                if(empty($retentionTemplateData)){
                    throw new \Exception('充值模板不存在,或者模板不属于该小程序');
                }
            }
            if(!empty($assistant_retention_template_id)){

                //查询副充值模板是否存在
                $retentionTemplateData = RechargeTemplate::query()->where(['id' => $assistant_retention_template_id,'company_id' => $company_id])->exists();
                if(empty($retentionTemplateData)){
                    throw new \Exception('充值模板不存在,或者模板不属于该小程序');
                }
            }
//            if($operation_mode == 2){
//                if($userInfo['id'] != 10020 && $userInfo['id'] != 10001) {
//                    throw new \Exception('系统暂时不支持IAA模式');
//                }
//            }

            //查询投放平台是否存在
            $dataSpreadPlatformData = DataSpreadPlatform::query()->where(['id' => $spread_platform_id])->exists();
            if(empty($dataSpreadPlatformData)){
                throw new \Exception('投放平台不存在');
            }
            $is_select_account = true;
            $old_account = '';
            if(!$is_update){
                $model->user_id = $userInfo['id'];
            }else{
                $old_account = $model->ad_account;
                //修改判断这个广告ID是否存在
                if ($ad_account == $old_account) {
                    $is_select_account = false;
                }
            }
            if($spread_platform_id == 1 && empty($ad_account)){
                //throw new \Exception('广告账户ID不能为空');
            }
            //2024-02-16
            if(!empty($ad_account)){
                if(!preg_match('/^\d+$/', $ad_account)){
                    //throw new \Exception('广告账户ID应为纯数字');
                }
            }

            //检查是否有重复的广告ID
            if($is_select_account && !empty($ad_account)){
                $checkSpreadInfo = DataSpread::query()->select(['id','name'])->where(['ad_account' => $ad_account])->first();
                if(!empty($checkSpreadInfo)){
                    //throw new \Exception('广告账户已经被绑定，请解绑后再重新绑定,被绑定的推广链接为:'.$checkSpreadInfo->name.',是否需要解绑？',SystemCode::SYSTEM_ERROR_AD_ACCOUNT);
                }else{
                    //同一个广告ID 不能同一天操作 判断这个广告账户最后一次操作时间
//                    $adAccountLog = DataSpreadAdAccountLog::query()->where(['ad_account' => $ad_account])
//                        ->where('created_at','>=',date('Y-m-d 00:00:00',time()))
//                        ->where('created_at','<=',date('Y-m-d 23:59:59',time()))
//                        ->first();
//                    if(!empty($adAccountLog)){
//                        throw new \Exception('此广告账户今日已操作过绑定/解绑操作,请明日再执行操作');
//                    }
                }
                $model->ad_account = $ad_account;
            }
            if(!empty($backhaul_setting_id) ){
                $model->backhaul_setting_id = $backhaul_setting_id;
            }
            $model->applet_id = $applet_id;
            $model->operation_mode = $operation_mode;
            $model->company_id = $company_id;
            $model->playlet_id = $playlet_id;
            $model->user_type = $user_type;
            $model->recharge_template_id = $recharge_template_id;
            $model->assistant_recharge_template_id = $assistant_recharge_template_id;
            $model->retention_template_id = $retention_template_id;
            $model->assistant_retention_template_id = $assistant_retention_template_id;
            $model->spread_platform_id = $spread_platform_id;
            $model->playlet_name = $playletData->name;
            $model->playlet_number = $playlet_number;
            $model->playlet_number_name =$playletEpisodesData->playlet_number_name;
            $model->playlet_number_num =$playlet_number_num;
            $model->playlet_number_num_pay =$playlet_number_num_pay;
            $model->recharge_template_type =$recharge_template_type;
            $model->name = $name;
            if($model->save()){

                if(!empty($ad_account)){
                    $is_insert = true;

                    if(!empty($old_account) && ($old_account == $ad_account)){
                        $is_insert = false;
                    }
                    if($is_insert){
                        $time = date('Y-m-d H:i:s',time());
                        $insertData[] = ['data_spread_id' => $model->id,'status' => 1,'ad_account' =>$ad_account,'created_at' => $time,'updated_at' => $time];
                        Db::table('data_spread_ad_account_log')->insert($insertData);
                    }
                }


                if(empty($model->route_key)){
                    $route_key = $this->generateRandomString(20);
                    $model->route_key = $route_key;
                    $model->wx_route = 'https://kyweb.kuaiyingbox.com/jump/'.$route_key;
                }
                if(empty($model->wx_link)){
                    $model->wx_link = 'pages/videopage/videopage?spread_id='.$model->id.'&pid='.$model->playlet_id.'&peid='.$model->playlet_number.'&aid='.$userInfo['id'].'&ut='.$user_type;
                }
                if($appletData->type == 2){
                    if(empty($model->dy_link)) {
                        $model->dy_link = 'sslocal://microapp?app_id='.$appletData->app_id.'&start_page=pages/videopage/videopage&spread_id='.$model->id.'&pid='.$model->playlet_id.'&peid='.$model->playlet_number.'&aid='.$userInfo['id'].'&ut='.$user_type.'&tt_album_id='.$playletData->album_id.'&tt_episode_id='.$playletEpisodesData->dy_episodes_id.'&app_id='.$appletData->app_id;
                    }
                    if(empty($model->dy_page)) {
                        $model->dy_page = 'pages/videopage/videopage';
                    }
                    if(empty($model->dy_parameter)) {
                        $model->dy_parameter = 'spread_id='.$model->id.'&pid='.$model->playlet_id.'&peid='.$model->playlet_number.'&aid='.$userInfo['id'].'&ut='.$user_type.'&tt_album_id='.$playletData->album_id.'&tt_episode_id='.$playletEpisodesData->dy_episodes_id.'&app_id='.$appletData->app_id;
                    }
                    if(empty($model->dy_route)) {
                        $query = array();
                        $query['spread_id'] = $model->id;
                        $query['pid'] = $model->playlet_id;
                        $query['peid'] = $model->playlet_number;
                        $query['aid'] = $userInfo['id'];
                        $query['ut'] = $user_type;
                        $query['tt_album_id'] = $playletData->album_id;
                        $query['tt_episode_id'] = $playletEpisodesData->dy_episodes_id;
                        $query['app_id'] = $appletData->app_id;
                        $queryStr = json_encode($query);
//                        $queryStr = addslashes($queryStr);
//                        var_dump($queryStr);
//                        $model->dy_route = 'test';
                        $model->dy_route =  $this->dygenerateLink($appletData,$queryStr);
                    }

                }
                $model->save();
                Db::commit();
                return $this->response(SystemCode::SYSTEM_SUCCESS);
            }else{
                Db::rollBack();
                return $this->response(SystemCode::SYSTEM_ERROR,'保存错误');
            }

        }catch (\Exception $e){
            Db::rollBack();
            if($e->getCode() == SystemCode::SYSTEM_ERROR_AD_ACCOUNT){
                return $this->response(SystemCode::SYSTEM_ERROR_AD_ACCOUNT,$e->getMessage());
            }else{
                return $this->response(SystemCode::SYSTEM_ERROR,$e->getMessage());
            }
        }

    }

    public function copy(DataSpread $dataSpreadInfo = null){
        Db::beginTransaction();
        try {

            //
            $name = $dataSpreadInfo->name;
            //存在
            if(strpos($name,'_')){

               $arr = explode('_',$name);
               $num = count($arr);
               $name = '';
               foreach ($arr as $key => $val){
                   if($key+1 == $num){
                       $name.='_'.(int)$val+1;
                   }else{
                       $name .= $val;
                   }
               }
            }else{
                $name = $name.'_1';
            }

            $appletData = Applet::query()->where(['id' => $dataSpreadInfo->applet_id])->first();

            $model = new DataSpread();
            $model->name = $name;
            $model->operation_mode = $dataSpreadInfo->operation_mode;
            $model->applet_id = $dataSpreadInfo->applet_id;
            $model->company_id = $dataSpreadInfo->company_id;
            $model->playlet_id = $dataSpreadInfo->playlet_id;
            $model->recharge_template_id = $dataSpreadInfo->recharge_template_id;
            $model->assistant_recharge_template_id = $dataSpreadInfo->assistant_recharge_template_id;
            $model->retention_template_id = $dataSpreadInfo->retention_template_id;
            $model->assistant_retention_template_id = $dataSpreadInfo->assistant_retention_template_id;
            $model->spread_platform_id = $dataSpreadInfo->spread_platform_id;
            $model->playlet_name = $dataSpreadInfo->playlet_name;
            $model->playlet_number_name = $dataSpreadInfo->playlet_number_name;
            $model->playlet_number = $dataSpreadInfo->playlet_number;
            $model->playlet_number_num = $dataSpreadInfo->playlet_number_num;
            $model->playlet_number_num_pay = $dataSpreadInfo->playlet_number_num_pay;
            $model->recharge_template_type = $dataSpreadInfo->recharge_template_type;
            $model->deleted = $dataSpreadInfo->deleted;
            $model->manager_id = $dataSpreadInfo->manager_id;
            $model->spread_id = $dataSpreadInfo->spread_id;
            $model->url = $dataSpreadInfo->url;
            $model->url_toutiao10 = $dataSpreadInfo->url_toutiao10;
            $model->url_toutiao20 = $dataSpreadInfo->url_toutiao20;
            $model->backhaul_setting_id = $dataSpreadInfo->backhaul_setting_id;
            $model->user_id = $dataSpreadInfo->user_id;
            $model->user_type = $dataSpreadInfo->user_type;
            $old_dy_params = '';

            if($appletData->type == 2){

                $old_dy_parameter = $dataSpreadInfo->dy_parameter;

                if(!empty($old_dy_parameter)){
                    parse_str($old_dy_parameter,$dy_params);
                    if(!empty($dy_params['tt_album_id']) && !empty($dy_params['tt_episode_id'])){
                        $old_dy_params = '&tt_album_id='.$dy_params['tt_album_id'].'&tt_episode_id='.$dy_params['tt_episode_id'];
                    }
                }
            }
            if($model->save()){
                $route_key = $this->generateRandomString(20);
                $model->route_key = $route_key;
                $model->wx_route = 'https://kyweb.kuaiyingbox.com/jump/'.$route_key;
                $model->wx_link = 'pages/videopage/videopage?spread_id='.$model->id.'&pid='.$model->playlet_id.'&peid='.$model->playlet_number.'&aid='.$model->user_id.'&ut='.$model->user_type;

                if($appletData->type == 2){
                    $model->dy_link = 'sslocal://microapp?app_id='.$appletData->app_id.'&start_page=pages/videopage/videopage&spread_id='.$model->id.'&pid='.$model->playlet_id.'&peid='.$model->playlet_number.'&aid='.$model->user_id.'&ut='.$model->user_type.$old_dy_params;
                    $model->dy_page = 'pages/videopage/videopage';
                    $model->dy_parameter = 'spread_id='.$model->id.'&pid='.$model->playlet_id.'&peid='.$model->playlet_number.'&aid='.$model->user_id.'&ut='.$model->user_type.$old_dy_params;
                }

                $model->save();
                Db::commit();
                return $this->response(SystemCode::SYSTEM_SUCCESS);
            }else{
                Db::rollBack();
                return $this->response(SystemCode::SYSTEM_ERROR,'复制失败');
            }
        }catch (\Exception $e){
            Db::rollBack();
            return $this->response(SystemCode::SYSTEM_ERROR,$e->getMessage());
        }
    }

    function generateRandomString($length = 10) {
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $string = '';
        for ($i = 0; $i < $length; $i++) {
            $string .= $characters[rand(0, strlen($characters) - 1)];
        }
        return substr(sha1($string), 0, $length);
    }

    public function batchSettings(Array $params){

        $data_spread_ids = $params['data_spread_ids'];
        $recharge_template_id = $params['recharge_template_id'] ?? '';
        $assistant_recharge_template_id = $params['assistant_recharge_template_id'] ?? '';
        $assistant_retention_template_id = $params['assistant_retention_template_id'] ?? '';
        $retention_template_id = $params['retention_template_id'] ?? '';
        $backhaul_setting_id = $params['backhaul_setting_id'] ?? '';
        $playlet_number_num = $params['playlet_number_num'] ?? '';
        $playlet_number_num_pay = $params['playlet_number_num_pay'] ?? '';
        $dataSpreadInfo = DataSpread::query()->whereIn('id',$data_spread_ids)->get();

        if($dataSpreadInfo->isNotEmpty()){

            //需要查询这个推广链接的短剧是否有限制默认付费集数
            if(!empty($playlet_number_num)){
                $errorMsg = [];
                foreach ($dataSpreadInfo as $item){

                    //查询这个短剧是否有对应的限制集数
                    $limitInfo = PlayletSpreadLimit::query()->where(['playlet_id' => $item->playlet_id])->first();

                    if(!empty($limitInfo)){

                        if($playlet_number_num > $limitInfo->pay_episodes_number){
                            $errorMsg[] = '推广链接 ID:'.$item->id.'付费集数大于默认付费集数，'.$limitInfo->playlet->name.'.默认付费集数为:'.$limitInfo->pay_episodes_number;
                        }
                    }
                }
            }
            if(!empty($errorMsg)){

                return $this->response(SystemCode::SYSTEM_ERROR_BATCH_SETTING,'批量配置错误',$errorMsg);
            }


            foreach ($dataSpreadInfo as $item){
                $is_update = false;
                if(!empty($recharge_template_id)){
                    if($recharge_template_id == 1){
                        $item->recharge_template_type = 1;
                        $item->recharge_template_id = 1;
                    }else{
                        $item->recharge_template_type = 2;
                        $item->recharge_template_id = $recharge_template_id;
                    }
                    $is_update = true;
                }

                if(!empty($playlet_number_num)){
                    $item->playlet_number_num = $playlet_number_num;
                    $is_update = true;
                }
                if(!empty($playlet_number_num_pay)){
                    $item->playlet_number_num_pay = $playlet_number_num_pay;
                    $is_update = true;
                }

                if(!empty($assistant_recharge_template_id)){
                    $item->assistant_recharge_template_id = $assistant_recharge_template_id;
                    $is_update = true;
                }
                //2024-03-14 新增挽留模板
                if(!empty($retention_template_id)){
                    $item->retention_template_id = $retention_template_id;
                    $is_update = true;
                }
                if(!empty($assistant_retention_template_id)){
                    $item->assistant_retention_template_id = $assistant_retention_template_id;
                    $is_update = true;
                }
                if(isset($backhaul_setting_id) && $backhaul_setting_id != ''){
                    $item->backhaul_setting_id = $backhaul_setting_id;
                    $is_update = true;
                }
                if($is_update){
                    $item->save();
                }
            }
            return $this->response(SystemCode::SYSTEM_SUCCESS, '成功');
        }else{
            return $this->response(SystemCode::SYSTEM_ERROR,'数据不存在');
        }
    }

    public function deliverybackhaulSetting($applet_id){
        //根据用户获取ID
        $userInfo = $this->getUserAppletInfo(2);
        $company_id = $userInfo['company_id'];

        $user_id = $userInfo['id'];
        $resultData[] = ['value' => 0,'label' => '不回传'];
        $query = DataBackhaulSetting::select(['id as value','name as label'])->where(['company_id' =>$company_id]);
        if($userInfo['role']['is_admin'] != 1){
            $query->where(['user_id' => $user_id]);
        }
        $returnData = $query->get()->toArray();
        if(!empty($returnData)){

            $resultData = array_merge($resultData,$returnData);
            return $this->response(SystemCode::SYSTEM_SUCCESS, '获取成功',$resultData);
        }else{
//            $resultData[] = ['value' => 0,'label' => '不回传'];
            return $this->response(SystemCode::SYSTEM_SUCCESS, '获取成功',$resultData);
//            return $this->response(SystemCode::SYSTEM_ERROR,'数据不存在');
        }
    }


    public function accountBind($dataSpreadInfo = null)
    {

        $ad_account = $dataSpreadInfo->ad_account;

        if(empty($ad_account)){
            return $this->response(SystemCode::SYSTEM_ERROR, '推广链接没有广告账户ID');
        }


        Db::beginTransaction();
        try {
            $dataSpreadInfo->ad_account = '';
            if ($dataSpreadInfo->save()) {
                $time = date('Y-m-d H:i:s', time());
                //插入绑定数据和解绑数据
                $insertData[] = ['data_spread_id' => $dataSpreadInfo->id, 'status' => 2, 'ad_account' => $ad_account, 'created_at' => $time, 'updated_at' => $time];
                Db::table('data_spread_ad_account_log')->insert($insertData);
                Db::commit();
                return $this->response(SystemCode::SYSTEM_SUCCESS);
            }
        } catch (\Exception $e) {
            Db::rollBack();
            return $this->response(SystemCode::SYSTEM_ERROR, $e->getMessage());
        }
    }
}